<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>车辆定位和轨迹</title>
<script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=E06eb9d756d0eafc722effb355657b4c"></script>
<jsp:include page="${pageContext.request.contextPath }/resource_path.jsp" flush="true"/>
</head>
<body>
	<div class="layui-form" style="margin: 10px">
		<table class="layui-table">
			<tr>
				<td>
					<label style="width: 100px;" class="layui-form-label">请选择配送单号</label>
					<div style="width: 250px; float: left; color: #5FB878">
						<select id="plate" name="plate" lay-filter="plate">
							<!-- <option value="">请选择</option> -->
						</select>
                    </div>
                    <input readonly class="layui-input" id="plate_inp" name="plate_inp" style="width: 100px; color: #5FB878">
				</td>
				<%--
					<td>
						<label style="width: 100px;" class="layui-form-label">行车历史记录</label>
						<div style="width: 190px; float: left; color: #5FB878">
							<select id="history_plate" name="history_plate" lay-filter="history_plate">
								<!-- <option value="">请选择</option> -->
							</select>
						</div>
						<input readonly class="layui-input" id="history_plate_inp" name="history_plate_inp" style="width: 100px; color: #5FB878">
					</td>
				--%>
			</tr>
		</table>
	</div>

	<div id="mapId" style="height: 700px;">
	    <script type="text/javascript">
		  	//经纬度数组
	    	var PointArr = [];
	    	
		    layui.use(['form','laydate','layer'], function(){
		        var form = layui.form;
		        //var laydate = layui.laydate;
		        //var layer = layui.layer;
		        
		        //查询所有的出库单
                $.ajax({
                    type: 'POST',
                    url: '${pageContext.request.contextPath}/car/queryDeliveryNodeByStatus.do',
                    //data: {id:data.value},
                    //dataType: 'json',
                    async: false,
                    success: function (data1){
                        var resultEntity1 = eval('(' +data1+ ')');
                        console.log(resultEntity1);
                        for (var i = 0; i < resultEntity1.length; i++) {
                            $("#plate").append("<option value='"+ resultEntity1[i].id +"'>"+ resultEntity1[i].number.substring(0,19) +"</option>");
                        }
                        form.render();
                    }
                });
		        
		        //根据出库单号查询正在配送的车辆经纬度
		        form.on('select(plate)', function(data) {
		        	//1.根据出库单号查询对应的车牌号
		        	$.ajax({
				        type: 'POST',
				        url: '${pageContext.request.contextPath}/car/queryPlateByOutStockId.do',
				        data: {id: data.value},
				        //dataType: 'json',
				        async: false,
				        success: function (data3){
				        	var plate3 = eval('(' +data3+ ')');
				            $("#plate_inp").val(plate3);
				        }
				    });
		        	//2.根据出库单id查询车辆的经纬度
		        	$.ajax({
				        type: 'POST',
				        url: '${pageContext.request.contextPath}/car/queryVehicleTransInfoByOutStockId.do',
				        data: {outstock_order_id: data.value},
				        dataType: 'json',
				        async: false,
				        success: function (data3){
				            if (PointArr.length == 0) {
                                PointArr[0] = {lng: 116.403694, lat: 39.914492};
							} else {
                                for (var j = 0; j < data3.length; j++) {
                                    PointArr[j] = {lng: data3[j].longitude, lat: data3[j].latitude};
                                }
							}
				        }
				    });

					//初始化地图组件
                    var map = new BMap.Map("mapId");
                    map.enableScrollWheelZoom(); 						// 开启鼠标滚轮缩放
                    map.addControl(new BMap.NavigationControl());       //添加平移缩放控件
                    map.addControl(new BMap.ScaleControl());            //添加比例尺控件
                    map.addControl(new BMap.OverviewMapControl());      //添加缩略地图控件
                    map.addControl(new BMap.MapTypeControl());
                    map.centerAndZoom("北京",15);					// 根据经纬度显示地图的范围
                    map.setViewport(PointArr);							// 根据提供的地理区域或坐标设置地图视野
                    addStartMarker(new BMap.Point(PointArr[0].lng, PointArr[0].lat),'起点',map);

			      	//先将终点坐标展示的mark对象定义
			        var carMk;
			        //小车行驶图标
			        var drivingPoint = new BMap.Icon("http://developer.baidu.com/map/jsdemo/img/car.png", new BMap.Size(52,26), {
			            //anchor : new BMap.Size(20, 45),
			            imageSize:new BMap.Size(52,26)
			        });
			        //终点图标
			        var terminalPoint = new BMap.Icon("https://mapopen-website-wiki.cdn.bcebos.com/homePage/images/service-icon2.png", new BMap.Size(40,50), {
			            anchor : new BMap.Size(20, 45),
			            imageSize:new BMap.Size(600,45),
			            imageOffset: new BMap.Size(-345, 0) 	// 设置图片偏移
			        });
			        var nowMarker;
			        var i = 0;
			        var interval = setInterval(function () {
			            if (i >= PointArr.length) {
			                clearInterval(interval);
			                return;
			            }
			            drowLine(map,PointArr[i],PointArr[i+1]);//画线调用
			            i = i + 1;
			        }, 1000);
		
			        //画线
			        function drowLine(map,PointArr,PointArrNext) {
			            if(PointArrNext!=undefined) {
			                var polyline = new BMap.Polyline(
			                	[
			                        new BMap.Point(PointArr.lng, PointArr.lat),
			                        new BMap.Point(PointArrNext.lng, PointArrNext.lat)
			                    ],
			                    {
			                        strokeColor: "blue",
			                        strokeWeight: 5,
			                        strokeOpacity: 0.5,
			                        strokeStyle: "dashed"
			                    });   
			            	//创建折线
			                map.addOverlay(polyline);
			                addMarkerEnd(new BMap.Point(PointArrNext.lng, PointArrNext.lat), '小车行驶', map, PointArrNext, new BMap.Point(PointArr.lng, PointArr.lat));//添加图标
			            }else {
			                addMarkerEnd(new BMap.Point(PointArr.lng, PointArr.lat), '终点', map);//添加终点图标
			            }
			        }
			        //添加起始图标
			        function addStartMarker(point, name, mapInit) {
			            if(name == "起点"){
			                var myIcon = new BMap.Icon("https://mapopen-website-wiki.cdn.bcebos.com/homePage/images/service-icon2.png", new BMap.Size(40,50),{//宽高
			                    anchor: new BMap.Size(20, 45),						// 这句表示图片相对于所加的点的位置mapStart
			                    imageSize:new BMap.Size(600, 45),					// 图标所用的图片的大小，此功能的作用等同于CSS中的background-size属性。可用于实现高清屏的高清效果
			                    //offset: new BMap.Size(-10, 45), 					// 指定定位位置
			                    imageOffset: new BMap.Size(-46, 0) 					// 设置图片偏移
			                });
			                window.marker = new BMap.Marker(point,{icon:myIcon});  	// 创建标注
			                mapInit.addOverlay(marker);               				// 将标注添加到地图中
			                //marker.setAnimation(BMAP_ANIMATION_BOUNCE); 			// 跳动的动画
			            }
			        }
			        //添加行驶和终点图标
			        function addMarkerEnd(point, name, mapInit, trackUnit, prePoint) {
			            if(name == "小车行驶"){
			                if(carMk){
			                    //先判断第一次进来的时候这个值有没有定义，有的话就清除掉上一次的。然后在进行画图标。第一次进来时候没有定义也就不走这块，直接进行画图标
			                    mapInit.removeOverlay(carMk);
			                }
			                carMk = new BMap.Marker(point,{icon:drivingPoint});  	// 创建标注
			                carMk.setRotation(trackUnit.route);						// trackUnit.route
			                //getAngle(point,prePoint);								// js求解两点之间的角度
			                carMk.setRotation(getAngle(point,prePoint)-90);			// 旋转的角度
			                mapInit.addOverlay(carMk);               				// 将标注添加到地图中
			                //carMk.setAnimation(BMAP_ANIMATION_BOUNCE); 			// 跳动的动画
			            }else {
			                mapInit.removeOverlay(carMk);
			                carMk = new BMap.Marker(point,{icon:terminalPoint});  	// 创建标注
			                mapInit.addOverlay(carMk);
			            }
			        }
			        //获得角度的函数
			        function getAngle(n,next){
			            var ret
			            var w1 = n.lat/180 * Math.PI
			            var j1 = n.lng/180 * Math.PI
		
			            var w2 = next.lat/180 * Math.PI
			            var j2 = next.lng/180 * Math.PI
		
			            ret = 4 * Math.pow(Math.sin((w1 - w2) / 2), 2) - Math.pow(Math.sin((j1 - j2) / 2) * (Math.cos(w1) - Math.cos(w2)), 2);
			            ret = Math.sqrt(ret);
		
			            // var temp = Math.sin(Math.abs(j1 - j2) / 2) * (Math.cos(w1) + Math.cos(w2));
			            var temp = Math.sin((j1 - j2) / 2) * (Math.cos(w1) + Math.cos(w2));
			            console.log(temp)
			            ret = ret/temp;
		
			            ret = Math.atan(ret) / Math.PI * 180 ;
			            ret += 90;
		
			            // 判定追踪单个点的具体情况,从而调整ret的值
			            if(j1-j2 < 0){
			                // console.log('j1<j2')
			                if(w1-w2 < 0){
			                    // console.log('w1<w2')
			                    ret;
			                }else{
			                    // console.log('w1>w2')
			                    ret = -ret+180;
			                }
			            }else{
			                // console.log('j1>j2')
			                if(w1-w2 < 0){
			                    // console.log('w1<w2')
			                    ret = 180+ret;
			                }else{
			                    // console.log('w1>w2')
			                    ret = -ret;
			                }
			            }
			            return ret ;
			        }
		        });
		        
		        /* —————————————————行车历史记录——————————————————— */
		        //查询已配送完成的出库单
		        /*$.ajax({
		            type: 'POST',
		            url: '${pageContext.request.contextPath}/car/queryVehicleTransInfoByStatus2.do',
		            //data: {id:data.value},
		            //dataType: 'json',
		            //async: false,
		            success: function (data2){
		            	var resultEntity2 = eval('(' +data2+ ')');
		            	//console.log(plate.length);
		            	for (var i = 0; i < resultEntity2.length; i++) {
                            $("#history_plate").append("<option value='"+ resultEntity2[i].outstock_order_id +"'>"+ resultEntity2[i].out_stock_num +"</option>");
                        }
		            	form.render();
		            }
		        });*/
		        
		        form.on('select(history_plate)', function(data) {
		        	console.log(data);
		        	PointArr = [];
		        	//1.根据出库单号查询对应的车牌号
		        	$.ajax({
				        type: 'POST',
				        url: '${pageContext.request.contextPath}/car/queryPlateByOutStockId.do',
				        data: {outstock_order_id: data.value},
				        //dataType: 'json',
				        async: false,
				        success: function (data4){
				        	var plate4 = eval('(' +data4+ ')');
				            $("#history_plate_inp").val(plate4);
				        }
				    });
		        	//2.根据出库单id查询车辆的经纬度
	        		$.ajax({
				        type: 'POST',
				        url: '${pageContext.request.contextPath}/car/queryVehicleTransInfoByOutStockId2.do',
				        data: {outstock_order_id: data.value},
				        dataType: 'json',
				        async: false,
				        success: function (data4){
				            for (var j = 0; j < data4.length; j++) {
				            	PointArr[j] = {lng: data4[j].longitude, lat: data4[j].latitude};
				            }
				        }
				    });
			    	var map = new BMap.Map("mapId");
			        map.enableScrollWheelZoom(); 						// 开启鼠标滚轮缩放
			        //map.centerAndZoom("西安", 8);
			        map.addControl(new BMap.NavigationControl());       // 添加平移缩放控件
			        map.addControl(new BMap.ScaleControl());            // 添加比例尺控件
			        map.addControl(new BMap.OverviewMapControl());      // 添加缩略地图控件
			        map.addControl(new BMap.MapTypeControl());
			        map.centerAndZoom(PointArr, 13);					// 根据经纬度显示地图的范围
			        map.setViewport(PointArr);							// 根据提供的地理区域或坐标设置地图视野
		
			        addStartMarker(new BMap.Point(PointArr[0].lng, PointArr[0].lat),'起点',map);
			      	//先将终点坐标展示的mark对象定义
			        var carMk;
			        //小车行驶图标
			        var drivingPoint = new BMap.Icon("http://developer.baidu.com/map/jsdemo/img/car.png", new BMap.Size(52,26), {
			            //anchor : new BMap.Size(20, 45),
			            imageSize:new BMap.Size(52,26)
			        });
			        //终点图标
			        var terminalPoint = new BMap.Icon("https://mapopen-website-wiki.cdn.bcebos.com/homePage/images/service-icon2.png", new BMap.Size(40,50), {
			            anchor : new BMap.Size(20, 45),
			            imageSize:new BMap.Size(600,45),
			            imageOffset: new BMap.Size(-345, 0) 	// 设置图片偏移
			        });
			        var nowMarker;
			        var i = 0;
			        var interval = setInterval(function () {
			            if (i >= PointArr.length) {
			                clearInterval(interval);
			                return;
			            }
			            drowLine(map,PointArr[i],PointArr[i+1]);//画线调用
			            i = i + 1;
			        }, 0.1);
		
			        //画线
			        function drowLine(map,PointArr,PointArrNext) {
			            if(PointArrNext!=undefined) {
			                var polyline = new BMap.Polyline(
			                	[
			                        new BMap.Point(PointArr.lng, PointArr.lat),
			                        new BMap.Point(PointArrNext.lng, PointArrNext.lat)
			                    ],
			                    {
			                        strokeColor: "blue",
			                        strokeWeight: 5,
			                        strokeOpacity: 0.5,
			                        strokeStyle: "dashed"
			                    });   
			            	//创建折线
			                map.addOverlay(polyline);
			                addMarkerEnd(new BMap.Point(PointArrNext.lng, PointArrNext.lat), '小车行驶', map, PointArrNext, new BMap.Point(PointArr.lng, PointArr.lat));//添加图标
			            }else {
			                addMarkerEnd(new BMap.Point(PointArr.lng, PointArr.lat), '终点', map);//添加终点图标
			            }
			        }
			        //添加起始图标
			        function addStartMarker(point, name, mapInit) {
			            if(name == "起点"){
			                var myIcon = new BMap.Icon("https://mapopen-website-wiki.cdn.bcebos.com/homePage/images/service-icon2.png", new BMap.Size(40,50),{//宽高
			                    anchor: new BMap.Size(20, 45),						// 这句表示图片相对于所加的点的位置mapStart
			                    imageSize:new BMap.Size(600, 45),					// 图标所用的图片的大小，此功能的作用等同于CSS中的background-size属性。可用于实现高清屏的高清效果
			                    //offset: new BMap.Size(-10, 45), 					// 指定定位位置
			                    imageOffset: new BMap.Size(-46, 0) 					// 设置图片偏移
			                });
			                window.marker = new BMap.Marker(point,{icon:myIcon});  	// 创建标注
			                mapInit.addOverlay(marker);               				// 将标注添加到地图中
			                //marker.setAnimation(BMAP_ANIMATION_BOUNCE); 			// 跳动的动画
			            }
			        }
			        //添加行驶和终点图标
			        function addMarkerEnd(point, name, mapInit, trackUnit,prePoint) {
			            if(name=="小车行驶"){
			                if(carMk){
			                    //先判断第一次进来的时候这个值有没有定义，有的话就清除掉上一次的。然后在进行画图标。第一次进来时候没有定义也就不走这块，直接进行画图标
			                    mapInit.removeOverlay(carMk);
			                }
			                carMk = new BMap.Marker(point,{icon:drivingPoint});  	// 创建标注
			                carMk.setRotation(trackUnit.route);						// trackUnit.route
			                //getAngle(point,prePoint);								// js求解两点之间的角度
			                carMk.setRotation(getAngle(point,prePoint)-90);			// 旋转的角度
			                mapInit.addOverlay(carMk);               				// 将标注添加到地图中
			                //carMk.setAnimation(BMAP_ANIMATION_BOUNCE); 			// 跳动的动画
			            }else {
			                mapInit.removeOverlay(carMk);
			                carMk = new BMap.Marker(point,{icon:terminalPoint});  	// 创建标注
			                mapInit.addOverlay(carMk);
			            }
			        }
			        //获得角度的函数
			        function getAngle(n,next){
			            var ret
			            var w1 = n.lat/180 * Math.PI
			            var j1 = n.lng/180 * Math.PI
		
			            var w2 = next.lat/180 * Math.PI
			            var j2 = next.lng/180 * Math.PI
		
			            ret = 4 * Math.pow(Math.sin((w1 - w2) / 2), 2) - Math.pow(Math.sin((j1 - j2) / 2) * (Math.cos(w1) - Math.cos(w2)), 2);
			            ret = Math.sqrt(ret);
		
			            // var temp = Math.sin(Math.abs(j1 - j2) / 2) * (Math.cos(w1) + Math.cos(w2));
			            var temp = Math.sin((j1 - j2) / 2) * (Math.cos(w1) + Math.cos(w2));
			            console.log(temp)
			            ret = ret/temp;
		
			            ret = Math.atan(ret) / Math.PI * 180 ;
			            ret += 90;
		
			            // 判定追踪单个点的具体情况,从而调整ret的值
			            if(j1-j2 < 0){
			                // console.log('j1<j2')
			                if(w1-w2 < 0){
			                    // console.log('w1<w2')
			                    ret;
			                }else{
			                    // console.log('w1>w2')
			                    ret = -ret+180;
			                }
			            }else{
			                // console.log('j1>j2')
			                if(w1-w2 < 0){
			                    // console.log('w1<w2')
			                    ret = 180+ret;
			                }else{
			                    // console.log('w1>w2')
			                    ret = -ret;
			                }
			            }
			            return ret ;
			        }
		        });
			});
	    </script>
	</div>
</body>
</html>
